'use client'

import React, { useRef } from 'react';
import { ComponentConfig } from './DroppedComponent';
import {
  TimelineEditor,
  MarqueeEditor,
  ImageEditor,
  CarouselEditor,
  VideoEditor,
  IframeEditor,
  NewsListEditor,
} from './editors';

interface PropertyEditorProps {
  component: ComponentConfig | null;
  onUpdateProperties: (properties: any) => void;
}

export default function PropertyEditor({ component, onUpdateProperties }: PropertyEditorProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);

  if (!component) {
    return (
      <div className="w-80 bg-white border-l border-gray-200 p-6">
        <div className="text-center text-gray-500">
          <div className="text-4xl mb-4">⚙️</div>
          <p className="text-lg font-medium">属性编辑器</p>
          <p className="text-sm">选择一个组件进行编辑</p>
        </div>
      </div>
    );
  }

  // 处理文件上传
  const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>, context?: { type: string, index?: number }) => {
    const file = event.target.files?.[0];
    if (!file) return;

    try {
      // 上传文件到服务器
      const formData = new FormData();
      formData.append('file', file);
      formData.append('folder', 'images');

      const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData,
      });

      const result = await response.json();

      if (!result.success || !result.data || !result.data.url) {
        console.error('上传失败:', result.message);
        alert('上传失败: ' + (result.message || '未知错误'));
        return;
      }

      const imageUrl = result.data.url;
      const newProperties = { ...component.properties };

      // 根据上下文设置不同的属性
      if (context) {
        switch (context.type) {
          case 'image':
            newProperties.src = imageUrl;
            break;
          case 'video':
            newProperties.src = imageUrl;
            break;
          case 'timeline':
            if (context.index !== undefined && newProperties.timelineData) {
              newProperties.timelineData = [...newProperties.timelineData];
              newProperties.timelineData[context.index] = {
                ...newProperties.timelineData[context.index],
                img: imageUrl
              };
            }
            break;
          case 'carousel':
            if (context.index !== undefined && newProperties.items) {
              newProperties.items = [...newProperties.items];
              newProperties.items[context.index] = {
                ...newProperties.items[context.index],
                src: imageUrl
              };
            }
            break;
          case 'marquee':
            if (context.index !== undefined && newProperties.images) {
              newProperties.images = [...newProperties.images];
              newProperties.images[context.index] = imageUrl;
            }
            break;
          case 'news-list':
            if (context.index !== undefined && newProperties.items) {
              newProperties.items = [...newProperties.items];
              newProperties.items[context.index] = {
                ...newProperties.items[context.index],
                image: imageUrl
              };
            }
            break;
        }
      }

      onUpdateProperties(newProperties);

      // 清空文件输入，以便可以再次选择同一文件
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    } catch (error) {
      console.error('上传过程中出错:', error);
      alert('上传过程中出错: ' + (error instanceof Error ? error.message : '未知错误'));
    }
  };

  const updateProperty = (key: string, value: any) => {
    onUpdateProperties({
      ...component.properties,
      [key]: value
    });
  };

  const renderPropertyEditor = () => {
    const editorProps = {
      properties: component.properties,
      updateProperty,
      handleFileSelect,
    };

    switch (component.type) {
      case 'timeline':
        return <TimelineEditor {...editorProps} />;
      case 'marquee':
        return <MarqueeEditor {...editorProps} />;
      case 'image':
        return <ImageEditor {...editorProps} />;
      case 'carousel':
        return <CarouselEditor {...editorProps} />;
      case 'video':
        return <VideoEditor {...editorProps} />;
      case 'iframe':
        return <IframeEditor {...editorProps} />;
      case 'news-list':
        return <NewsListEditor {...editorProps} />;
      default:
        return <div className="text-gray-500">未知的组件类型</div>;
    }
  };

  return (
    <div className="w-80 bg-white border-l border-gray-200 p-6 h-[calc(100vh-150px)] overflow-y-auto">
      <div className="mb-4">
        <h2 className="text-lg font-semibold text-gray-900 flex items-center">
          <span className="mr-2">⚙️</span>
          属性编辑器
        </h2>
        <p className="text-sm text-gray-600 mt-1">
          正在编辑: {component.type} 组件
        </p>
      </div>

      <div className="space-y-4">
        {renderPropertyEditor()}
      </div>
    </div>
  );
}
